package com.gc.ykqx.service.presenter;


import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.gc.ykqx.service.entity.Fore;
import com.gc.ykqx.service.manager.DataManager;
import com.gc.ykqx.service.view.ForeView;
import com.gc.ykqx.service.view.View;

import java.util.List;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by wsd on 2017/9/30.
 */

public class ForePresenter implements Presenter {
    private DataManager manager;
    private CompositeSubscription mCompositeSubscription;
    private Context mContext;
    private ForeView mForeView;
    private Fore mFore;

    public ForePresenter(Context context) {
        this.mContext = context;
    }

    @Override
    public void onCreate() {
        manager = new DataManager(mContext);
        mCompositeSubscription = new CompositeSubscription();

    }

    @Override
    public void onStart() {

    }

    @Override
    public void onStop() {
        if (mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }

    }

    @Override
    public void pause() {

    }

    @Override
    public void attachView(View view) {
        mForeView = (ForeView) view;

    }

    @Override
    public void attachIncomingIntent(Intent intent) {

    }

    public void getFore(final String fileType) {
        mCompositeSubscription.add(manager.getFore(fileType)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Fore>() {
                    @Override
                    public void onCompleted() {
                        if (mFore != null) {
                            List<Fore.DSBean> ds = mFore.getDS();
                            for (int i=0;i<ds.size();i++){
                                String ft = ds.get(i).getFILE_Type();
                                if (!ft.equals(fileType)){
                                    mFore.getDS().remove(i);
                                }
                            }
                            mForeView.onSuccess(mFore,fileType);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onNext(Fore fore) {
                        mFore = fore;
                    }
                }));
    }
}
